#!/usr/local/bin/ruby

require 'applescript'
require 'ropt'
require 'find'

# 
# @return array
def labels(path, indices)

	labelled = Array.new()
	result = false

	files = Array.new()

	i = 1
	snippet = "tell application \"Finder\" \n set _list to {} \n"
	list = '';

	bundles = AppleScript.bundles
	Find.find(path) do |file|

		puts file + ' is a symlink (should be ' + File.readlink(file) + ')' if (File.symlink?(file))

		# check to see if we're in a bundle
		Find.prune if (bundles.index(File.extname(File.basename(File.dirname(file)))) != nil) 

		# avoid hidden files, etc.
		next if (File.basename(file).index('.') == 0)

		files[i] = file

		fileType = 'file'		
		if (File.directory?(file))
			fileType = bundles.index(File.extname(file)) == nil ? 'folder' : 'file'
		end

		varname = '_p' + i.to_s
		snippet = snippet + 'set ' + varname + " to 0 \n try\n set " + varname + ' to label index of ' + fileType + ' POSIX file ' + file.dump + "\n on error \n \n end try \n"
		i = i + 1
  end

	snippet = snippet + 'set _list to {';  

	j = 1
	(files.length - 1).times do 
		snippet = snippet + (j > 1 ? ',' : '') + ' _p' + j.to_s
		j = j + 1
  end
  snippet = snippet + "} \n _list \n end tell"
  
	script = AppleScript.new(snippet)
	result = script.run()

	result = result.split(',')
	i = 1
	result.each  { |r|
		r = r.to_i
		labelled.push(files[i]) if (indices.index(r) != nil)
		i = i + 1
	}

	return labelled	
end

def usage
	puts "usage"
end

opt = ROpt.parse(ARGV, "orwbpgy", 'orange', 'red', 'yellow', 'blue', 'purple', 'green', 'gray') || usage

indices = Array.new()
indices.push(AppleScript::ORANGE_LABEL) if opt['o'] || opt['orange']
indices.push(AppleScript::RED_LABEL) if opt['r'] || opt['red']
indices.push(AppleScript::YELLOW_LABEL) if opt['w'] || opt['yellow']
indices.push(AppleScript::BLUE_LABEL) if opt['b'] || opt['blue']
indices.push(AppleScript::PURPLE_LABEL) if opt['p'] || opt['purple']
indices.push(AppleScript::GREEN_LABEL) if opt['g'] || opt['green']
indices.push(AppleScript::GRAY_LABEL) if opt['y'] || opt['gray']

if (indices.length == 0) 
	indices = AppleScript.labels.keys
end

path = Dir.getwd()

if (opt.args.length > 0) 
	opt.args.each { |a|
		path = File.expand_path(a)
		files = labels(path, indices)
		puts files.join("\n")	if files.length > 0
	}
else
		files = labels(path, indices)
		puts files.join("\n")	if files.length > 0
end
